<?php

namespace App;

use App\Exceptions\BusinessException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

trait VerifyRequestInput
{
    /**
     * 验证boolean
     * @param $key
     * @param  null  $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyBoolean($key,$default = null)
    {
        return $this->verifyData($key,$default,'boolean');
    }

    /**
     * 验证枚举
     * @param $key
     * @param $default
     * @param  array  $enum
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyEnums($key, $default, $enum = [])
    {
        return $this->verifyData($key, $default, Rule::in($enum));
    }

    /**
     * 验证非空数组
     * @param $key
     * @param $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyArrayNotEmpty($key, $default = null)
    {
        return $this->verifyData($key, $default, 'array|min:1');
    }

    /**
     * 验证int型
     * @param $key
     * @param $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyInteger($key, $default = null)
    {
        return $this->verifyData($key, $default, 'integer');
    }

    /**
     * 验证字符串
     * @param $key
     * @param $default
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyString($key, $default = null)
    {
        return $this->verifyData($key, $default, 'string');
    }

    /**
     * 验证封装
     * @param $key
     * @param $default
     * @param $rule
     * @return mixed|null
     * @throws BusinessException
     */
    public function verifyData($key, $default, $rule)
    {
        $value = request()->input($key, $default);
        $validator = Validator::make([$key, $value], [
            $key => $rule
        ]);
        if (is_null($default) && is_null($value)) {
            return $value;
        }
        if ($validator->fails()) {
            throw new BusinessException(CodeResponse::FAIL);
        }
        return $value;
    }
}
